package com.hzdl.house_mgr.controller;

import com.hzdl.house_mgr.bean.Admin;
import com.hzdl.house_mgr.bean.LogInfo;
import com.hzdl.house_mgr.service.AdminService;
import com.hzdl.house_mgr.service.LogInfoService;
import com.hzdl.house_mgr.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

@Controller
public class LoginController {

    @Autowired
    private HttpServletRequest req;

    @Autowired
    private AdminService adminService;

    @Autowired
    private LogInfoService logInfoService;

    @RequestMapping("loginInit")
    public String loginInit(){
        return "system/login";
    }

    @RequestMapping("autoYzm")
    public void autoYzm(HttpSession session, OutputStream os){
        String yzm = VerifyCodeUtils.generateVerifyCode(4);
        session.setAttribute("session_yzm",yzm);
        try {
            VerifyCodeUtils.outputImage(120,40,os,yzm);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("chkYzm")
    @ResponseBody
    public String chkYzm(String yzm,HttpSession session){
        Object session_yzm = session.getAttribute("session_yzm");
        if(session_yzm!=null){
            String sYzm = String.valueOf(session_yzm);
            if(yzm.equalsIgnoreCase(sYzm)){
                return "0";
            }
        }
        return "1";
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(Admin admin, String code, HttpSession session){

        Object session_yzm = session.getAttribute("session_yzm");
        if(session_yzm!=null){
            String sYzm = String.valueOf(session_yzm);
            if(!code.equalsIgnoreCase(sYzm)){
                return "2";
            }
        }

        Admin loginAdmin = adminService.login(admin);
        if(loginAdmin == null){
            return "";
        }else {
            //把对象数据保存到session中
            session.setAttribute("session_admin",loginAdmin);

            //记录登录日志，向sys_log_login插入数据
            LogInfo logInfo = new LogInfo();
            logInfo.setLoginName(loginAdmin.getRealName()+"-"+loginAdmin.getAdminName());
            logInfo.setLoginTime(new Date());
            String remoteAddr = req.getRemoteAddr();
            logInfo.setLoginIp(remoteAddr);
            logInfoService.insertLogInfo(logInfo);
            return "1";
        }
    }

    @RequestMapping("loginOut")
    public String loginOut(HttpSession session){
        /*session.removeAttribute("session_admin");
        session.removeAttribute("session_yzm");*/
        session.invalidate();//让session过期
        return "system/login";
    }
}
